'use strict';

angular.module('afasApp')
.factory('ServicesLS', ['localStorageService', function (localStorageService) {

  var data = function(entity) {
    var dataInStore = localStorageService.get(entity);
    var data = angular.fromJson(dataInStore) || [];
    return data;
  };

  var doRequest = function(entity, object) {
    return localStorageService.add(entity, angular.toJson(object, true));
  };

  return {
    getItems: function (entity) {
      return data(entity);
    },
    getItem: function(entity, id){
      return data(entity)[id];
    },
    add: function(entity, data){
      var dataNew = data(entity);
      dataNew.push(data);
      doRequest(entity, dataNew);
    },
    update: function(entity, data, index){
      var dataNew = data(entity);
      dataNew[index] = data;
      doRequest(entity, dataNew);
    },
    delete: function(entity, index){
      var dataNew = data(entity);
      dataNew.splice(index, 1);
      doRequest(entity, dataNew);
    },
    create: function(entity, string){
      return localStorageService.add(entity, string);
    },
    get: function(entity){
      return localStorageService.get(entity);
    },
    remove: function(entity){
      return localStorageService.remove(entity);
    }
  };
}]);
